package server

import (
	"core/auth"
	"core/config"
	"core/corestruct"
	"core/coreutil"
	"core/db"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"golang.org/x/net/context"
	"time"
)

func GinFirst() gin.HandlerFunc {
	return func(c *gin.Context) {

		start := time.Now()
		c.Set("start", start)
		path := c.Request.URL.Path
		query := c.Request.URL.RawQuery
		var su = &corestruct.HttpSession{}
		var mycontext = &corestruct.HttpContext{
			Http:    c,
			Session: su,
		}
		dbctx := context.WithValue(c, "MyContext", mycontext)
		var db = db.DbMaster.WithContext(dbctx)
		mycontext.DB = db

		var token = c.Request.Header.Get("token")
		if token != "" {
			su, err := auth.GetSession(token, true, mycontext)
			if err == nil {
				mycontext.Session = su
			}
		}

		//var myc = context.WithValue(c, "MyContext", mycontext)
		c.Set("MyContext", mycontext)

		defer func() {
			cost := time.Since(start)
			if err := recover(); err != nil {
				HttpErr(mycontext, err)

				return
			}

			//直接忽略后面的判断
			if config.Config.Server.Mode != "debug" {
				return
			}
			coreutil.Logger.Debug(path,
				zap.Int("status", c.Writer.Status()),
				zap.String("method", c.Request.Method),
				zap.String("path", path),
				zap.String("query", query),
				zap.String("ip", c.ClientIP()),
				zap.String("user-agent", c.Request.UserAgent()),
				zap.String("errors", c.Errors.ByType(gin.ErrorTypePrivate).String()),
				zap.Duration("cost", cost),
			)
		}()

		c.Next()

	}
}
